package org.rency.mq.activemq.listener.factory;

import org.rency.mq.activemq.exception.MessageHandleException;
import org.rency.mq.activemq.listener.handler.impl.AbstractHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import javax.jms.*;

class DefaultMessageListener implements MessageListener {
	private static Logger log = LoggerFactory.getLogger(DefaultMessageListener.class);
	private AbstractHandler messageHandler;

	public void onMessage(Message message) {
		Assert.notNull(messageHandler, "MessageHandler cannot be null.");
		
		if(log.isDebugEnabled()){
			log.debug("The handler is: " + messageHandler.getClass());
		}
		
		Object request = null;
		if (message instanceof ObjectMessage) {
			ObjectMessage objMessage = (ObjectMessage) message;

			try {
				request = objMessage.getObject();
			} catch (JMSException e) {
				log.error("Listenning message error. Message: " + message, e);
			}
		}else if(message instanceof TextMessage){
			TextMessage textMessage = (TextMessage)message;
			
			try {
				request = textMessage.getText();
			} catch (JMSException e) {
				log.error("Listenning message error. Message: " + message, e);
			}
		}else{
			log.error("Incorrect message type. Message: " + message);
			
			throw new MessageHandleException("Incorrect message type. Message: " + message);
		}
		
		log.info("Listen on message: " + request);
		
		if(request == null) return;

		messageHandler.handle(request);
	}

	public AbstractHandler getMessageHandler() {
		return messageHandler;
	}

	public void setMessageHandler(AbstractHandler messageHandler) {
		this.messageHandler = messageHandler;
	}
}
